<?php


namespace App\Web\Model;


use App\Facades\UrlCrypt;
use App\Service\Dict;
use App\Service\DictConstant;
use App\Web\Model\CaseResume as CaseResumeModel;
use EchoPHP\Facades\Db;
use App\Web\Model\Resume as ResumeModel;
use EchoPHP\Facades\Redis;

class Manager extends Model {

    /**
     * 根据用户简历ID获取简历信息，如果没有下载，抹去重要个人信息
     * @param $oprId
     * @param $resumeId
     * @param null $field
     * @return array
     */
    public function getManagerListWithChkDownload($oprId, $resumeId, $field = null) {
        $resumeList = $this->getManagerListByResumeId($resumeId, $field);
        $resumeList = $this->chkDownload($oprId, $resumeList);
        return $resumeList;
    }

    /**
     * 根据简历id获取简历（s_manager）表信息 注意本方法最多支持150个简历id，超出此限制应该考虑使用selectClosure方法
     * @param $resumeId
     * @param string $field
     * @return array
     */
    public function getManagerListByResumeId($resumeId, $field = null) {
        if(empty($resumeId)){
            return [];
        }
        $field = $field ?? 'cname,managerid,userid51job as resumeid,relationaccid as accountid,birthday,gender,area,funtype,workindustry,degree,lastupdate,expsalaryfrom,expsalaryto,major,school,company,division,position,workyear';
        $resumeId = array_slice($resumeId, 0, 150);
        $inFlag = substr(str_repeat('?,', count($resumeId)), 0, -1);
        $sql = 'SELECT ' . $field . ' FROM s_manager WHERE userid51job IN(' . $inFlag . ') AND status=?';
        $var = array_merge($resumeId, ['01']);

        $list = Db::connect('jyrpo_oracle')->select($sql, $var);

        //对查询结果进行排序，防止返回顺序不是传入顺序
        $managerList = [];
        foreach ($list as $item) {
            $managerList[$item['resumeid']] = $item;
        }

        $list = [];
        foreach ($resumeId as $item) {
            if (isset($managerList[$item])) {
                $list[] = $managerList[$item];
            }
        }
        unset($managerList);

        $dict = new Dict();
        $attributes = [
            'area' => DictConstant::DD_CITY_COUNTY,
            'funtype' => DictConstant::DD_FUNCTYPE,
            'gender' => DictConstant::DD_GENDER,
            'workindustry' => DictConstant::DD_INDUSTRY,
            'major' => DictConstant::DD_MAJOR,
            'degree' => DictConstant::DD_DEGREE,
            'expectarea' => DictConstant::DD_CITY_COUNTY,
        ];
        $dict->rowTrans($list, $attributes);
        foreach ($list as &$item) {
            if (isset($item['birthday'])) {
                if (!empty($item['birthday'])) {
                    $item['age'] = $this->computeAge($item['birthday']);
                } else {
                    $item['age'] = '';
                }
            }
            if (isset($item['workyear'])) {
                $item['workyear_origin'] = $item['workyear'];
                $item['workyear'] = $this->computeWorkyear($item['workyear']);
            }

            $item['token'] = UrlCrypt::generateToken([$item['resumeid']]);
        }

        return $list;
    }

    /**
     * 根据精英网简历id获取简历数据
     * @param $managerId
     * @param null $field
     * @return array
     */
    public function getManagerListByMgrId($managerId, $field = null) {
        $field = $field ?? 'cname,managerid,userid51job as resumeid,relationaccid as accountid,birthday,gender,area,funtype,workindustry,degree,lastupdate,expsalaryfrom,expsalaryto,major,school,company,division,position,workyear';
        $managerId = array_slice($managerId, 0, 150);
        $inFlag = substr(str_repeat('?,', count($managerId)), 0, -1);
        $sql = 'SELECT ' . $field . ' FROM s_manager WHERE managerid IN(' . $inFlag . ') AND status=?';
        $var = array_merge($managerId, ['01']);

        $list = Db::connect('jyrpo_oracle')->select($sql, $var);

        //对查询结果进行排序，防止返回顺序不是传入顺序
        $managerList = [];
        foreach ($list as $item) {
            $managerList[$item['managerid']] = $item;
        }

        return array_values($managerList);
    }

    /**
     * 判断是否下载(上传)该简历
     * @param $oprId
     * @param array $managerList
     * @param bool $hideCnameIdNoDown
     * @param bool $includeTeam
     * @return array
     */
    public function chkDownload($oprId, array $managerList, $hideCnameIdNoDown = true, $includeTeam = true) {
        $resumeIds = [];
        foreach ($managerList as $item) {
            $resumeIds[] = $item['resumeid'];
        }
        if (!empty($resumeIds)) {
            $resumeModel = new ResumeModel();
            $alreadyDownList = $resumeModel->getDownloadResumeId($oprId, $resumeIds, $includeTeam);
        } else {
            $alreadyDownList = [];
        }
        foreach ($managerList as &$item) {
            if (in_array($item['resumeid'], $alreadyDownList)) {
                $item['alreadydown'] = 1;
            } else {
                $item['alreadydown'] = 0;
                if ($hideCnameIdNoDown) {
                    $item['cname'] = '';
                    $item['email'] = '';
                    $item['mobilephone'] = '';
                }
            }
        }
        return $managerList;
    }


    /**
     * 判断是否已读该简历
     * @param $oprId
     * @param array $managerList
     * @return array
     */
    public function chkRead($oprId, array $managerList) {
        $resumeIds = [];
        foreach ($managerList as $item) {
            $resumeIds[] = $item['resumeid'];
        }
        if (empty($resumeIds)) {
            return $managerList;
        }

        $redisObj = Redis::connect('readresume');

        $resumeModel = new ResumeModel();

        $readKey = $resumeModel->getReadResumeKey(true);

        //当前季度已读情况。
        $result = @$redisObj->HMGET('rd_' . $oprId . '_' . $readKey['now'], $resumeIds);
        if (!empty($result) && is_array($result)) {
            foreach ($managerList as &$item) {
                $item['isread'] = 0;
                if (isset($result[$item['resumeid']]) && $result[$item['resumeid']] !== false) {
                    $item['isread'] = 1;
                    unset($resumeIds[$item['resumeid']]);
                }
            }
        }
        if (empty($resumeIds)) {
            return $managerList;
        }

        //尝试上一季度已读情况。
        $result = @$redisObj->HMGET('rd_' . $oprId . '_' . $readKey['prev'], $resumeIds);
        if (!empty($result) && is_array($result)) {
            foreach ($managerList as &$item) {
                if (isset($result[$item['resumeid']]) && $result[$item['resumeid']] !== false) {
                    $item['isread'] = 1;
                }
            }
        }

        return $managerList;
    }

    /**
     * 计算年龄
     * @param $birthday
     * @return int
     */
    public function computeAge($birthday) {
        $birthday = date('Y-m-d', strtotime($birthday));
        $current = date('Y-m-d');
        $birthdayArr = explode('-', $birthday);
        $currentArr = explode('-', $current);

        if ($currentArr[1] > $birthdayArr[1] || ($currentArr[1] == $birthdayArr[1] && $currentArr[2] >= $birthdayArr[2])) {
            $age = $currentArr[0] - $birthdayArr[0];
        } else {
            $age = $currentArr[0] - $birthdayArr[0] - 1;
        }
        return $age;
    }

    /**
     * @param $workyear
     * @return false|int|string
     */
    public function computeWorkyear($workyear) {
        if ($workyear == '' || $workyear == '9999') {
            return '无工作经验';
        }
        $current = date('Y');
        $workyear = $current - $workyear;
        return $workyear == 0 ? 1 : $workyear;
    }

    /**
     * 判断该简历已在职位中
     * @param array $managerList
     * @return array
     */
    public function chkInCase(array $managerList) {
        $caseResumeModel = new CaseResumeModel();
        foreach ($managerList as &$item) {
            //通过Redis判断该简历是否加入过职位
            $result = $caseResumeModel->getResumeInCaseCountByRedis($item['resumeid']);
            $item['incase'] = $result !== false && $result > 0 ? 1 : 0;
        }
        return $managerList;

        /*
        $resumeIds = array_column($managerList, 'resumeid');
        $existResumeIds = [];
        if (!empty($resumeIds)) {
            $existResumeIds = array_column((new CaseResume())->InCaseResume($resumeIds), 'resumeid');
        }
        foreach ($managerList as &$item) {
            $item['incase'] = in_array($item['resumeid'], $existResumeIds) ? 1 : 0;
        }
        return $managerList;
        */
    }
}